<template>
  <TresGroup :rotation="[-Math.PI * 0.5, 0, Math.PI * 0.09]">
    <TresMesh :geometry="mergedGeometry">
      <TresMeshMatcapMaterial :matcap="matcapTexture" />
    </TresMesh>
  </TresGroup>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { TextureLoader } from "three";
import * as BufferGeometryUtils from "three/addons/utils/BufferGeometryUtils.js";

const props = defineProps({
  blocks: {
    type: Array,
    required: true,
  },
});

// 使用 ref 存储纹理
const matcapTexture = ref(null);

// 在组件挂载后加载纹理
onMounted(async () => {
  try {
    // 使用 useLoader 加载纹理
    const loader = new TextureLoader();
    const texture = await new Promise((resolve, reject) => {
      loader.load(
        "./model_assets/C7C7D7_4C4E5A_818393_6C6C74-512px.png",
        resolve,
        undefined,
        reject
      );
    });

    // 将加载的纹理赋值给 ref
    matcapTexture.value = texture;
  } catch (error) {
    console.error("纹理加载失败:", error);
  }
});

// 合并几何体
const mergedGeometry = computed(() => {
  // 确保有可用的 blocks 和 geometries
  if (!props.blocks || props.blocks.length === 0) return null;

  const geometries = props.blocks
    .filter(
      (item) => item.children && item.children[0] && item.children[0].geometry
    )
    .map((item) => item.children[0].geometry);

  // 确保有有效的几何体可合并
  if (geometries.length === 0) return null;

  return BufferGeometryUtils.mergeGeometries(geometries);
});
</script>
